<?php
/**
 * Joomla! 1.5 component ArticleCashRewards
 *
 * @version $Id: listing.php 2009-05-10 01:47:01 svn $
 * @author Maverick
 * @package models
 * @subpackage ArticleCashRewards
 * @license GNU/GPL
 * Website: http://www.boddunan.com
 *
 * Review and approve the articles and assign points and cash rewards.
 * Users can see their articles and the points/cash rewards assigned in the front-end module.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

if(!class_exists('ContentHelperRoute')) require_once (JPATH_SITE . '/components/com_content/helpers/route.php');  

class ArticleCashRewardsModelReferrals extends JModel {

	var $_total = null; 
	var $_pagination = null;
    var $_error = null;
	
	function __construct(){
	
		parent::__construct();
		global $mainframe, $option;
	
		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest($option.'.limitstart', 'limitstart', 0, 'int');

		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

    function addLevel(){
        global $mainframe, $option;
        $db =& JFactory::getDBO();
        
        $level_desc = JRequest::getVar( 'level_desc', null, 'post', 'STRING');
        $level_articles = JRequest::getVar( 'level_value', '0', 'post', 'INTEGER');
        $level_amount = JRequest::getVar( 'level_amount', '0', 'post', 'FLOAT');
        $level_status = JRequest::getVar('level_status', 0, 'post', 'BOOLEAN');

        $query = 'INSERT INTO ' . TABLE_ACR_REFEREE_RULES . '(description, articles, amount, published)' .
            ' VALUES("' . $level_desc . '",' . $level_articles . ',' . $level_amount . ',' . $level_status . ')';
        $db->setQuery($query);
        if(!$db->query()){
            $this->_error = "Unable to add level: " . $db->getErrorMsg();
            return false;
        }

        return true;
    }

    function getLevels() {
	    
    	global $mainframe, $option;
    	
    	// Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();
        
		$query = 'SELECT id, description, articles, amount, published FROM '. TABLE_ACR_REFEREE_RULES;

		$db->setQuery($query);
		$rows = $db->loadObjectList();

		return $rows;
    }

    function getApprovedRules(){
        global $mainframe, $option;

    	// Get a database object
		$db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$query = 'SELECT id, description FROM '.
            TABLE_ACR_REFEREE_RULES . ' WHERE published=1';

		$db->setQuery($query);
		$rows = $db->loadObjectList();

		return $rows;
    }

    function getReferralReports($status){
	  	global $mainframe, $option;;
        $db =& JFactory::getDBO();
		$user =& JFactory::getUser();

		$query = 'SELECT ar.id AS id, u1.username AS referral, u2.username as referredby,' .
            ' al.id as ruleid, al.description AS rulename, ar.status, '.
            ' al.articles as articles, al.amount as amount FROM '. TABLE_ACR_REFERRALS . ' ar' .
            ' LEFT JOIN ' . TABLE_ACR_REFEREE_RULES . ' al ON ar.level=al.id' .
            ' LEFT JOIN #__users u1 ON ar.userid=u1.id' .
            ' LEFT JOIN #__users u2 ON ar.referredby=u2.id' .
            ' WHERE ar.status IN (' . $status . ') ORDER BY u1.username ASC, u2.username ASC, al.id ASC';
//echo $query;
		$db->setQuery($query, $this->getState('limitstart'), $this->getState('limit'));
		$rows = $db->loadObjectList();

        $query = 'SELECT count(*) FROM ' . TABLE_ACR_REFERRALS . ' WHERE status=' . $status;
        $db->setQuery($query);
        $this->_total = $db->loadResult();

		return $rows;
    }

    function processReferralPayments(){
        
        global $mainframe, $option;
        $db =& JFactory::getDBO();
        $result = null;

        $query = 'SELECT id, description, amount, articles FROM ' . TABLE_ACR_REFEREE_RULES .
            ' WHERE published=1';
        $db->setQuery($query);
        $rules = $db->loadObjectList();
        $flag=true;
        foreach($rules  as $rule){
            $query_base = 'INSERT INTO ' . TABLE_ACR_REFERRALS .
                        ' (userid,referredby,level,amount,status)' .
                        ' SELECT t.userid, t.referredby, "' . $rule->id . '" AS level, "' .
                        $rule->amount . '" AS amount, ' . STATUS_PENDING . ' AS status FROM';
                        
            if(strcmp($rule->description, REFEREE_LEVEL_REGISTERED) == '0'){
                $query = $query_base . ' (SELECT aup2.userid AS userid, aup1.userid AS referredby FROM'.
                    ' #__alpha_userpoints aup1 LEFT JOIN #__alpha_userpoints aup2 ON' .
                    ' aup1.referreid=aup2.referraluser WHERE aup2.referraluser IS NOT NULL) t' .
                    ' WHERE (SELECT COUNT(*) FROM ' . TABLE_ACR_REFERRALS . ' ar' .
                    ' WHERE ar.userid=t.userid AND ar.level=' . $rule->id . ')=0';
                $db->setQuery($query);
                if(!$db->query()){
                    $flag = false;
                }
            }else if(strcmp($rule->description, REFEREE_LEVEL_ACTIVATED) == '0'){
                $query = $query_base . ' (SELECT aup2.userid AS userid, aup1.userid AS referredby FROM'.
                    ' #__alpha_userpoints aup1 LEFT JOIN #__alpha_userpoints aup2 ON' .
                    ' aup1.referreid=aup2.referraluser WHERE aup2.referraluser IS NOT NULL) t,' .
                    ' #__users u WHERE t.referredby=u.id AND u.block=0 AND ' .
                    ' (SELECT COUNT(*) FROM ' . TABLE_ACR_REFERRALS . ' ar' .
                    ' WHERE ar.userid=t.userid AND ar.level=' . $rule->id . ')=0';
                $db->setQuery($query);
                if(!$db->query()){
                    $flag = false;
                }
            }else if(strcmp($rule->description, REFEREE_LEVEL_PAID) == '0'){
                $query = $query_base . ' (SELECT aup2.userid AS userid, aup1.userid AS referredby FROM'.
                    ' #__alpha_userpoints aup1 LEFT JOIN #__alpha_userpoints aup2 ON' .
                    ' aup1.referreid=aup2.referraluser WHERE aup2.referraluser IS NOT NULL) t' .
                    ' WHERE (SELECT COUNT(*) FROM ' . TABLE_ACR_REFERRALS . ' ar' .
                    ' WHERE ar.userid=t.userid AND ar.level=' . $rule->id . ')=0' .
                    ' AND (SELECT COUNT(*) FROM ' . TABLE_ACR_PAYMENTS . ' ap WHERE ap.payee_id = t.userid)>0';
                $db->setQuery($query);
                
                if(!$db->query()){
                    $flag = false;
                }
            }else if(strcmp($rule->description, REFEREE_LEVEL_POST_ARTICLES) == '0'){
                $query = $query_base . ' (SELECT aup2.userid AS userid, aup1.userid AS referredby FROM'.
                    ' #__alpha_userpoints aup1 LEFT JOIN #__alpha_userpoints aup2 ON' .
                    ' aup1.referreid=aup2.referraluser WHERE aup2.referraluser IS NOT NULL) t' .
                    ' WHERE (SELECT * FROM ' . TABLE_ACR_REFERRALS . ' ar' .
                    ' WHERE ar.userid=t.userid AND ar.level=' . $rule->id . ')=0 AND (SELECT COUNT(*) FROM ' .
                    TABLE_ACR_CONTENT . ' ac, #__content c WHERE ac.article_id=c.id AND'.
                    ' c.created_by = t.userid AND ac.cash>0)>=' . $rule->articles;
//$this->_error.="|||" . $query;
                $db->setQuery($query);
                if(!$db->query()){
                    $flag = false;
                }
            }

        }
      
        return false;;
    }

    function setReferralApprovalStatus($status, $cid){
        $db =& JFactory::getDBO();

        $referrals = implode(',', $cid);
        $query = 'UPDATE ' . TABLE_ACR_REFERRALS . ' SET status=' . $status .
            ' WHERE id IN (' . $referrals . ')';
        $db->setQuery($query);
        if(!$db->query()){
            $this->_error = $db->getErrorMsg();
            return false;
        }else{
            return true;
        }
    }

    function setRuleStatus($status, $rules){

        $db =& JFactory::getDBO();

        $rules_str = implode(',', $rules);
        $query = 'UPDATE ' . TABLE_ACR_REFEREE_RULES . ' SET published=' . $status .
            ' WHERE id IN (' . $rules_str . ')';
        $db->setQuery($query);
        if(!$db->query()){
            return false;
        }else{
            return true;
        }
    }

    function removeRules($rules){
        $db =& JFactory::getDBO();

        $rules_str = implode(',', $rules);
        $query = 'DELETE FROM ' . TABLE_ACR_REFEREE_RULES . ' WHERE id IN (' . $rules_str . ')';
        $db->setQuery($query);
        if(!$db->query()){
            return false;
        }else{
            return true;
        }
    }

    function getTotal(){

	    if (empty($this->_total)) {
	    
			$db =& JFactory::getDBO();

			$query = 'SELECT COUNT(*) FROM ' . TABLE_ACR_REFEREE_RULES;
			$db->setQuery( $query );
			$this->_total = $db->loadResult();
		}			
		return $this->_total;
	}
	  
	function getPagination(){
        global $mainframe,$option;
		$pnls = JRequest::getVar( 'pnlimitstart', 'null');
		
		if($pnls == 'null'){
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal(), 0, $this->getState('limit') );
		    $this->setState('limitstart', 0);
            $mainframe->setUserState("$option.filter_order", 'aw.date_submitted');
		}

		// Load the content if it doesn't already exist
		if (empty($this->_pagination)) {
		    jimport('joomla.html.pagination');
		    $this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}    

    function getError(){
        return $this->_error;
    }
}
?>